package com.dormitory.javadormitory.common;

import com.dormitory.javadormitory.exception.CustomException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import tk.mybatis.mapper.util.StringUtil;

@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    //权限验证，拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (StringUtil.isEmpty(token)){
            token = request.getParameter("token");
        }
        if (StringUtil.isEmpty(token)){

//            throw new CustomException("无token，请重新登录");
            throw new CustomException(ResultEnum.UNAUTHORIZED.getCode(),ResultEnum.UNAUTHORIZED.getMessage());
        }
        if (JwtTokenUtils.validateToken(token)){
            HttpSession session = request.getSession();
            session.setAttribute("userId", JwtTokenUtils.getUserIdFromToken(token));
            return true;
        }else {
            throw new CustomException(ResultEnum.UNAUTHORIZED.getCode(),ResultEnum.UNAUTHORIZED.getMessage());
        }
    }
}
